package My

import (
	"fmt"
	"db2s/ETL"
	"db2s/global"
	"strings"
	"sync/atomic"
)

type TableIndex struct{}

type colAndWhereResult struct {
	selectColumn, asSelectColumn, whereCondition []string
	orderByColumn                                string
}

func (my TableIndex) selectCol(selectC []string) (r string) {
	var selectIndexColumn []string
	for _, v := range selectC {
		selectIndexColumn = append(selectIndexColumn, fmt.Sprintf("\"%v\"", v))
	}
	return strings.Join(selectIndexColumn, ",")
}
func (my TableIndex) orderByNull(s global.StartPart) (r string) {
	return fmt.Sprintf(" order by `%v`", strings.Join(s.WhereGenerate.IndexColumn, "`,`"))
}
func (my TableIndex) whereSplicing(whereCondition []string) (r string) {
	if len(whereCondition) > 0 {
		return fmt.Sprintf(" and %v", strings.Join(whereCondition, " and "))
	}
	return ""
}

/*
StartPart 库下查询表的索引列数据的始末位置，并进行去重排序
*/
func (my TableIndex) StartPart(s global.StartPart) (result any, err error) {
	var (
		event = "[mysqlStartPart]"
		rep   = global.StartPartReturnResult{}
		res   colAndWhereResult
		f1    any
	)
	if res, err = colAndWhere(s); err != nil {
		return
	}
	rep.BaseResult.Sql = fmt.Sprintf("select %v \n"+
		"from %v where 1= 1 \n"+
		"%v %v limit %d,1",
		strings.Join(res.selectColumn, ","),
		tableObject(s.TableInfo.Schema, s.TableInfo.BackendTableName, s.TableInfo.PartitionName),
		my.whereSplicing(res.whereCondition), my.orderByNull(s), atomic.LoadInt64(s.Limit.Pagination))
	if rep.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
		Ss:           s,
		Event:        event,
		SelectSqlStr: rep.BaseResult.Sql,
		Expect:       ETL.Map,
		ShardName:    "single",
	}); err != nil {
		return
	}
	rep.Result = f1.(map[string]any)
	return rep, nil
}
